"""
    @Author  ：思念 
    @File    ：2、爱奇艺影片信息爬取.py
    @Date    ：2024/12/17 20:03 
"""

import requests
import pymongo


class AiQiYi:
    def __init__(self):
        self.client = pymongo.MongoClient("mongodb://localhost:27017/")
        self.db = self.client["py_spider"]["aqy_movie_list"]
        try:
            self.db.drop()  # 使用 drop 方法删除集合
            print("删除成功")
        except Exception as e:
            print(f"删除失败: {e}")
        self.api_url = "https://pcw-api.iqiyi.com/search/recommend/list"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
        }

    def get_movie_info(self, params_attrs):
        result_json = requests.get(self.api_url, params=params_attrs, headers=self.headers).json()
        return result_json

    def parse_movie_info(self, response):
        movie_list = response["data"]["list"]
        for movie in movie_list:
            item = dict()
            item['title'] = movie['title']
            item['playUrl'] = movie['playUrl']
            item['description'] = movie['description']
            self.save_movie_info(item)

    def save_movie_info(self, item):
        try:
            self.db.insert_one(item)
            print("插入成功")
        except Exception as e:
            print(e)
            print("插入失败")

    def close_spider(self):
        self.client.close()
        print("爬虫结束")

    def main(self):
        print("爬虫开始")
        for page_num in range(1, 6):
            params_dict = {
                "channel_id": "2",
                "data_type": "1",
                "mode": "11",
                "page_id": page_num,
                "ret_num": "48",
                "session": "e06d9851e931da6f3143f4b88de4f196",
                "three_category_id": "15;must"
            }
            info = self.get_movie_info(params_dict)
            self.parse_movie_info(info)
        self.close_spider()


"""
    爬取爱奇艺的24小时热播电影信息，并保存到MongoDB数据库中。
"""
if __name__ == '__main__':
    aqy = AiQiYi()
    aqy.main()
